package org.hl.mall.auth.data.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.hl.mall.auth.data.domain.Member;
import org.hl.mall.auth.data.domain.MemberDetails;
import lombok.extern.slf4j.Slf4j;
import org.hl.mall.auth.data.mapper.MemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Slf4j
@Component
public class TulingUserDetailService implements UserDetailsService {


    @Autowired
    private MemberMapper memberMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        if(StringUtils.isEmpty(userName)) {
            log.warn("用户登陆用户名为空:{}",userName);
            throw new UsernameNotFoundException("用户名不能为空");
        }

        //todo 调会员服务接口去拿数据
        Member umsMember = getByUsername(userName);

        if(null == umsMember) {
            log.warn("根据用户名没有查询到对应的用户信息:{}",userName);
        }

        log.info("根据用户名:{}获取用户登陆信息:{}",userName,umsMember);

        MemberDetails memberDetails = new MemberDetails(umsMember);

        return memberDetails;
    }


    public Member getByUsername(String username) {
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<Member>();
        queryWrapper.eq(Member::getUsername,username);
        return memberMapper.selectOne(queryWrapper);
    }

    public Member loadUserByMobile(String mobile) {
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<Member>();
        queryWrapper.eq(Member::getUsername,mobile);
        return memberMapper.selectOne(queryWrapper);
    }
}
